package com.xiaoshu.filter;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.time.StopWatch;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 功能说明： Spring cloud 配置全局过滤器信息；
 *
 * @ com.xiaoshu.filter
 * <p>
 * Original @Author: deane.jia-贾亮亮,@2020/9/29@14:10
 * <p>
 * Copyright (C)2012-@2020 深圳小树盛凯科技 All rights reserved.
 */
@Component
@Slf4j
public class CustomizeGlobalFilter implements GlobalFilter {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String path = exchange.getRequest().getURI().getPath();
        log.info("[CustomizeGlobalFilter] 访问的接口：{}", path);
        StopWatch clock = new StopWatch();
        clock.start();
        // then的内容会在过滤器返回的时候执行，即最后执行
        return chain.filter(exchange).then(Mono.fromRunnable(() -> {
            clock.stop();
            log.info("[ {} ] 接口的访问耗时：{} /ms", path, clock.getTime());
        }));
    }
}
